package com.gz.mylife.app;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.widget.LoadingCover;
import com.gz.mylife.widget.OfflineDialog;
import com.gz.mylife.widget.LoadingCover.OnLoadingCoverRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zl.smartmall.library.IAddress;
import com.zl.smartmall.library.concurrent.ThreadExecutor;
import com.zl.smartmall.library.listener.GetAddresssFromServerListener;
import com.zl.smartmall.library.po.ProvinceInfo;
import com.zl.smartmall.library.vo.NewAddressDao;

public class NewAddressActivity extends BaseActivity implements
		OnItemClickListener, OnLoadingCoverRefreshListener {
	private static final String TAG = NewAddressActivity.class.getSimpleName();

	private static final int REQ_PROVINCE = 1;
	private static final int REQ_CITY = 2;
	private static final int REQ_COUNTY = 3;

	private LayoutInflater mInflater;
//	private int mReqCode = Define.REQ_UNKNOW;
	private int mReqType;
	private int mCurrentPid;

	private MyHandler mHandler;

	private PullToRefreshListView mPullList;
	private LinearLayout mllAddress;
	private TextView mTvAddress;
	private LoadingCover mLoadingCover;
	private OfflineDialog mAlertOfflineDialog;
	private Dialog mLoadingData;
	private MyAdapter mAdapter;
	private String mStrAddress = "";
	private String mProvince = "";
	private String mCity = "";
	private String mCounty = "";
	private NewAddressDao mDao;

	List<ProvinceInfo> mProvinceList;
	List<ProvinceInfo> mCityList;
	List<ProvinceInfo> mCountyList;
	List<ProvinceInfo> mDataTemp;
	
	private GetAddressListener mListener;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_address);
		init();
		initView();
		mListener = new GetAddressListener(this);
		ThreadExecutor.getInstance().execute(new Runnable() {
			
			@Override
			public void run() {
				List<ProvinceInfo> list = mDao.getProvinceList();
				Message msg = mHandler.obtainMessage(1, list);
				mHandler.sendMessage(msg);
			}
		});
		
	}

	private void init() {
		mInflater = getLayoutInflater();
//		mActionBar.setTitle("所在地址");
		setActionbarTitle("所在地址", false);
		mHandler = new MyHandler(this);
		mProvinceList = new ArrayList<ProvinceInfo>();
		mCityList = new ArrayList<ProvinceInfo>();
		mCountyList = new ArrayList<ProvinceInfo>();
		mDataTemp = new ArrayList<ProvinceInfo>();
		mDao = new NewAddressDao(getApplicationContext());
	}

	private void initView() {
		mPullList = (PullToRefreshListView) findViewById(R.id.list_address);
		mAdapter = new MyAdapter();
		mPullList.setAdapter(mAdapter);
		mllAddress = (LinearLayout) findViewById(R.id.ll_address);
		mTvAddress = (TextView) findViewById(R.id.tv_address);
		mllAddress.setVisibility(View.GONE);
		mPullList.setOnItemClickListener(this);
		mLoadingCover = (LoadingCover) findViewById(R.id.layout_loading_cover);
		mLoadingCover.setOnLoadingCoverRefreshListener(this);
		;
		mAlertOfflineDialog = (OfflineDialog) mInflater.inflate(
				R.layout.offline_dialog, null);
		mLoadingData = new Dialog(getApplicationContext(), R.style.DialogTheme);
		mLoadingData.setCanceledOnTouchOutside(false);
		mLoadingData.setContentView(R.layout.loading_data_dialog);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.release();
		mListener.release();
	}

	private static class MyHandler extends Handler {

		private NewAddressActivity mOuter;

		public MyHandler(NewAddressActivity outer) {
			mOuter = outer;
		}

		@Override
		public void handleMessage(android.os.Message msg) {
			if (mOuter == null) {
				return;
			}
			switch (msg.what) {
			case 1:// 刷新adapter
				List<ProvinceInfo> list = (List<ProvinceInfo>) msg.obj;
				if (list != null && list.size() > 0) {
					mOuter.mProvinceList.clear();
					mOuter.mProvinceList.addAll(list);
					mOuter.mLoadingCover.onRefreshSuccess();
					mOuter.mReqType = REQ_PROVINCE;
					mOuter.mAdapter.notifyDataSetChanged();
				} else {
					IAddress.getInstance().getProvinces(REQ_PROVINCE, 0, mOuter.mListener);
				}
				break;
			case 2:
				List<ProvinceInfo> list2 = (List<ProvinceInfo>) msg.obj;
				if (list2 != null && list2.size() > 0) {
					mOuter.mCityList.clear();
					mOuter.mCityList.addAll(list2);
					mOuter.mLoadingData.dismiss();
					mOuter.mReqType = REQ_CITY;
					mOuter.mAdapter.notifyDataSetChanged();
				} else {
					IAddress.getInstance().getCities(REQ_CITY,mOuter.mCurrentPid, mOuter.mListener);
				}
				break;
			case 3:
				List<ProvinceInfo> list3 = (List<ProvinceInfo>) msg.obj;
				if (list3 != null && list3.size() > 0) {
					mOuter.mCountyList.clear();
					mOuter.mCountyList.addAll(list3);
					mOuter.mLoadingData.dismiss();
					mOuter.mReqType = REQ_COUNTY;
					mOuter.mAdapter.notifyDataSetChanged();
				} else {
					IAddress.getInstance().getCounTies(REQ_COUNTY, mOuter.mCurrentPid, mOuter.mListener);
				}
				break;

			default:
				break;
			}
		};

		public void release() {
			new WeakReference<NewAddressActivity>(mOuter);
		}
	}


	private class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			switch (mReqType) {
			case REQ_PROVINCE:
				return mProvinceList.size();
			case REQ_CITY:
				return mCityList.size();
			case REQ_COUNTY:
				return mCountyList.size();
			}
			return 0;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater
						.inflate(R.layout.new_address_item, null);
				holder = new ViewHolder();
				holder.name = (TextView) convertView.findViewById(R.id.tv_name);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			ProvinceInfo info = null;
			switch (mReqType) {
			case REQ_PROVINCE:
				info = mProvinceList.get(position);
				break;
			case REQ_CITY:
				info = mCityList.get(position);
				break;
			case REQ_COUNTY:
				info = mCountyList.get(position);
				break;
			}
			holder.name.setText(info.getName());
			return convertView;
		}

		private class ViewHolder {
			TextView name;
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		switch (mReqType) {
		case REQ_PROVINCE:
				ProvinceInfo provinceInfo = mProvinceList.get((int) id);
				mCurrentPid = provinceInfo.getCityId();
				if (mCurrentPid == 182 || mCurrentPid == 183
						|| mCurrentPid == 203 || mCurrentPid == 190) {
					if (mCurrentPid == 182) {
						mStrAddress = "北京市" + " ";
						mCurrentPid = 215;
					} else if (mCurrentPid == 183) {
						mStrAddress = "天津市" + " ";
						mCurrentPid = 234;
					} else if (mCurrentPid == 203) {
						mStrAddress = "重庆市" + " ";
						mCurrentPid = 2464;
					} else if (mCurrentPid == 190) {
						mStrAddress = "上海市" + " ";
						mCurrentPid = 1022;
					}
					mllAddress.setVisibility(View.VISIBLE);
					mTvAddress.setText(mStrAddress);
					mProvince = mStrAddress;
					mReqType = REQ_COUNTY;
					clearAdapter();
					
					ThreadExecutor.getInstance().execute(new Runnable() {
						
						@Override
						public void run() {
							List<ProvinceInfo> list = mDao.getListByPid(mCurrentPid);
							Message msg = mHandler.obtainMessage(3, list);
							mHandler.sendMessage(msg);
						}
					});
				} else {
					mStrAddress += provinceInfo.getName() + " ";
					mllAddress.setVisibility(View.VISIBLE);
					mTvAddress.setText(mStrAddress);
					mProvince = provinceInfo.getName();
					mReqType = REQ_CITY;
					clearAdapter();
					ThreadExecutor.getInstance().execute(new Runnable() {
						
						@Override
						public void run() {
							List<ProvinceInfo> list = mDao.getListByPid(mCurrentPid);
							Message msg = mHandler.obtainMessage(2, list);
							mHandler.sendMessage(msg);
						}
					});
				}
			break;
		case REQ_CITY:
				ProvinceInfo cityInfo = mCityList.get((int) id);
				mStrAddress += cityInfo.getName() + " ";
				mCurrentPid = cityInfo.getCityId();
				mTvAddress.setText(mStrAddress);
				mCity = cityInfo.getName();
				mReqType = REQ_COUNTY;
				clearAdapter();
//				List<ProvinceInfo> list = mDao.getListByPid(mCurrentPid);
				ThreadExecutor.getInstance().execute(new Runnable() {
					
					@Override
					public void run() {
						List<ProvinceInfo> list = mDao.getListByPid(mCurrentPid);
						Message msg = mHandler.obtainMessage(3, list);
						mHandler.sendMessage(msg);
					}
				});
			break;
		case REQ_COUNTY:
			mCounty = mCountyList.get((int) id).getName();
			mStrAddress += mCounty;
			Intent intent = new Intent();
			// intent.putExtra("address", mStrAddress);
			intent.putExtra("province", mProvince);
			intent.putExtra("city", mCity);
			intent.putExtra("county", mCounty);
			setResult(100, intent);
			finish();
			break;

		default:
			break;
		}
	}

	public void clearAdapter() {
		mProvinceList.clear();
		mCityList.clear();
		mCountyList.clear();
		mAdapter.notifyDataSetChanged();
	}

	@Override
	public void onLoadingCoverRefresh() {
		IAddress.getInstance().getProvinces(REQ_PROVINCE, 0, mListener);
	}

	private static class GetAddressListener extends
			GetAddresssFromServerListener {
		private NewAddressActivity mOuter;

		public GetAddressListener(NewAddressActivity outer) {
			this.mOuter = outer;
		}
		
		public void release(){
			new WeakReference<NewAddressActivity>(mOuter);
		}

		@Override
		public void onResponseSuccess(final List<ProvinceInfo> infos) {
			if(mOuter == null){
				return;
			}
			//第一步将数据保存到数据库（异步操作）
			ThreadExecutor.getInstance().execute(new Runnable() {
				
				@Override
				public void run() {
					mOuter.mDao.insert(infos);
				}
			});
			
			switch (mOuter.mListener.getRequestCode()) {
			case FIRST://省
				mOuter.mProvinceList.clear();
				mOuter.mProvinceList.addAll(infos);
				mOuter.mLoadingCover.onRefreshSuccess();
				mOuter.mReqType = REQ_PROVINCE;
				break;
			case PULL://市
				mOuter.mCityList.clear();
				mOuter.mCityList.addAll(infos);
				mOuter.mLoadingData.dismiss();
				mOuter.mReqType = REQ_CITY;
				break;
			case SCROLL://县
				mOuter.mCountyList.clear();
				mOuter.mCountyList.addAll(infos);
				mOuter.mReqType = REQ_COUNTY;
				break;

			default:
				break;
			}
			mOuter.mAdapter.notifyDataSetChanged();
		}

		@Override
		public void onNoMoreData() {
			if(mOuter == null){
				return;
			}
			switch (mOuter.mListener.getRequestCode()) {
			case FIRST://省
				mOuter.mLoadingCover.onRefreshFailed();
				break;
			case PULL://市
				mOuter.mLoadingData.dismiss();
				break;
			case SCROLL://县
				mOuter.mLoadingData.dismiss();
				break;

			default:
				break;
			}
		}

		@Override
		public void onNoNetWork() {
			if(mOuter == null){
				return;
			}
			switch (mOuter.mListener.getRequestCode()) {
			case FIRST://省
				mOuter.mLoadingCover.onRefreshFailed();
				break;
			case PULL://市
				mOuter.mLoadingData.dismiss();
				break;
			case SCROLL://县
				mOuter.mLoadingData.dismiss();
				break;

			default:
				break;
			}
			Toast.makeText(mOuter.getApplicationContext(), Define.MSG_NO_NETWORK, Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onOffline() {
			if(mOuter == null){
				return;
			}
			switch (mOuter.mListener.getRequestCode()) {
			case FIRST://省
				mOuter.mLoadingCover.onRefreshFailed();
				mOuter.mAlertOfflineDialog.show();
				break;
			case PULL://市
				mOuter.mLoadingData.dismiss();
				mOuter.mAlertOfflineDialog.show();
				break;
			case SCROLL://县
				mOuter.mLoadingData.dismiss();
				mOuter.mAlertOfflineDialog.show();
				break;

			default:
				break;
			}
		}

		@Override
		public void onResponseFailed() {
			if(mOuter == null){
				return;
			}
			switch (mOuter.mListener.getRequestCode()) {
			case FIRST://省
				break;
			case PULL://市
				break;
			case SCROLL://县
				break;

			default:
				break;
			}
		}

	}
}
